package cn.ibdsr.human.websocket;

import cn.ibdsr.human.interceptor.SpringContextHolder;
import cn.ibdsr.human.service.DataCenterService;
import cn.ibdsr.human.service.JobService;
import cn.ibdsr.human.transfer.platform.LatestJobItem;
import cn.ibdsr.human.util.RedisUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @description:
 * @author: cdl
 * @email: iamcimon@qq.com
 * @date: 2021/8/11 15:58
 */
@DependsOn("springContextHolder")
@Component
@ServerEndpoint("/data-center-screen")
@Slf4j
public class WebSocket {
    private Session session;
    private DataCenterService dataCenterService = SpringContextHolder.getBean(DataCenterService.class);
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);
        log.info("【websocket消息】有新的连接，总数：{}", webSocketSet.size());
        sendMessage();
    }

    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        log.info("【websocket消息】连接断开，总数：{}", webSocketSet.size());
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【websocket消息】收到客户端发来的消息：{}", message);
    }

    synchronized public void sendMessage() {
        if (webSocketSet.size() > 0) {
            String message = dataCenterService.getDataCenterData();
            log.info("【websocket消息】广播消息：{}", message);
            for (WebSocket webSocket : webSocketSet) {
                try {
                    webSocket.session.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}